<?php

namespace App\Http\Resources;

use App\Models\Report;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Str;

class ReportResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $data = [
            'id' => $this->id,
            'key' => $this->key,
            'technician_id' => $this->technician_id,
            'technician_name' => $this->technician_name,
            'technician_short_name' => $this->technician_short_name,
            'technician_height' => $this->technician_height,
            'technician_birth_year' => $this->technician_birth_year,
            'tecnhician_age' => $this->technician_birth_year ? (date('Y') - $this->technician_birth_year) : '',
            'club_id' => $this->club_id,
            'club_name' => $this->club_name,
            'club_short_name' => $this->club_short_name,
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            'created_at_human' => createdAt($this->created_at),
            'action_date' => $this->action_date,
            'action_time' => substr($this->action_time, 0, strrpos($this->action_time, ':')),
            'topic' => new TopicResource($this->whenLoaded('topic')),
            'user' => new UserResource($this->whenLoaded('user')),
        ];
        $values = [];
        $content = '';
        foreach (Report::$values as $type => $configs) {
            $field = "{$type}_value";
            $value = $this->{$field};
            $item = [
                'label' => $configs['label'],
                'value' => $value,
                'type' => 'value',
            ];
            $values[] = $item;

            $field = "{$type}_description";
            $value = $this->{$field};
            $item = [
                'label' => $configs['description_label'],
                'value' => $value,
                'type' => 'description',
            ];
            $values[] = $item;
            $content .= $value;
        }
        $data['values'] = $values;
        $data['content'] = Str::limit($content, 100);

        return $data;

    }
}
